//引入axios的核心库以及内部封装好的数据类型

import axios, { AxiosInstance, AxiosRequestConfig } from "axios";
//引入封装好的接口类型
import { ResultData } from './interface'
import qsString from 'querystring'
import router from "@/router";

//定义配置对象
let config = {
    baseURL:"/api"
}

class Http {
    http: AxiosInstance
    //构造器
    constructor(config:AxiosRequestConfig) {
        //重新实例
        this.http = axios.create(config)
        // 设置请求拦截
        this.http.interceptors.request.use((req) => { 
            if(req.url != '/userlogin'){
                let user:any =sessionStorage.getItem('userInfo');
                req.headers.authorization = JSON.parse(user).token
            }
            return req
        })
        // 设置响应拦截
        this.http.interceptors.response.use((res) => {
           
            if (res.data.msg == "请设置请求头,并携带验证字符串") {
                alert(res.data.msg);
                //强制跳转到登录
               router.push("/login")
              } else if (res.data.msg == "登录已过期或访问权限受限") {
                alert(res.data.msg);
                 //强制跳转到登录
                 router.push("/login")
              } else {
                //一定要记得返回
                return res.data;
              }
           
        })
    }

    get<T>(url:string,params?:object):Promise<ResultData<T>>{
        return this.http.get(url,{
            params
        })
    }

    post<T>(url:string,params?:any,isFile:boolean=false):Promise<ResultData<T>>{
        let data:any = {}
        if(isFile){
            data = new FormData()
            for(const[key,val] of Object.entries(params)){
                data.append(key,val)
            }
        }else{
            data=qsString.stringify(params)
        }
        return this.http.post(url,data)
    }
}

export default new Http(config)